package cn.jekun.shop.web.service;

import java.sql.Types;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.EncryptUtil;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.MD5;
import cn.jekun.component.base.validator.annotation.Num;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.RsSms;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.component.core.service.ScmService;
import cn.jekun.component.core.service.gen.RsSmsService;
import cn.jekun.component.core.validator.annotation.Password;
import cn.jekun.shop.common.service.ShopBaseService;

/**
 * 账户设置
 * @author twj
 *
 */
@Service(AccountSafeService.BEAN_NAME)
public class AccountSafeService extends ShopBaseService{
	public static final String BEAN_NAME = "cn.jekun.shop.web.service.AccountSafeService";
	public static final String NAMESPACE="RS_USER";
	@Override
	public String getNamespace() {
		return NAMESPACE;
	}
	@Resource(name = RsSmsService.BEAN_NAME)
	RsSmsService rsSmsService;
	@Resource(name = ScmService.BEAN_NAME)
	private ScmService scmService;
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Transactional
	public JSONObject resetLoginPwd(@RsUser.AnnoUserId String userId,@MD5 String newPwd,@MD5 String oldPwd) {
		JSONObject jsonObject = new JSONObject();
		if (StringUtils.isBlank(userId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户编码不能为空");
		}
		if (StringUtils.isBlank(oldPwd)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"旧密码不能为空");
		}
		if (StringUtils.isBlank(newPwd)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"新密码不能为空");
		}
		Map formMap = new HashMap();
		formMap.put(RsUser.COL_USER_ID, userId);
		SqlUtis.prepareSql(formMap, "", SqlUtis.getSQL(formMap, "a."
				+ RsUser.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ)
				);
		RsUser user = this.one(formMap);
		
		if(user == null){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户不存在");
		}
		if(!user.getPassword().equals(oldPwd)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"旧密码输入有误");
		}
		RsUser rsUser = new RsUser();
		rsUser.setPassword(newPwd);
		formMap.put("rsUser", rsUser);
		int totals = this.update(formMap);
		if(totals != 1){
			return executeRerutnFail(jsonObject);
		}
		//同步开店用户到scm系统
    	RsUser tempUser = this.rsUserService.one(userId);
    	//判断当前操作人是否为店长角色
    	if(this.scmService.isSJ(userId)){
    		boolean flag = this.scmService.synDataToScm(tempUser);
    		if(!flag){
    			log.info("#######用户数据到SCM同步失败#########");
    		}else{
    			log.info("#######用户数据到SCM同步成功#########");
    		}
    		
    	}
		return executeRerutn(jsonObject);
	}
	/**
	 * 
	 * @param userId
	 * @param email
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Transactional
	public JSONObject setEmial(@RsUser.AnnoUserId String userId, @RsUser.AnnoEmail String email) {
		JSONObject jsonObject = new JSONObject();
		if (StringUtils.isBlank(userId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户编码不能为空");
		}
		if (StringUtils.isBlank(email)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"email地址不能为空");
		}
		Map formMap = new HashMap();
		formMap.put(RsUser.COL_USER_ID, userId);
		SqlUtis.prepareSql(formMap, "", SqlUtis.getSQL(formMap, "a."
				+ RsUser.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ)
				);
		if(!this.exists(formMap)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户不存在");
		}
		RsUser rsUser = new RsUser();
		rsUser.setEmail(email);
		formMap.put("rsUser", rsUser);
		int totals = this.update(formMap);
		if(totals != 1){
			return executeRerutnFail(jsonObject);
		}
		return executeRerutn(jsonObject);
	}
	/**
	 * 绑定手机
	 * @param userId
	 * @param mobile
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Transactional
	public JSONObject setMobile(@RsUser.AnnoUserId String userId, @RsUser.AnnoMobile String mobile,@Num(length=6,message="短信验证码格式不正确")String validateCode) {
		JSONObject jsonObject = new JSONObject();
		RsUser rsUser = new RsUser();
		Map tempMap = new HashMap();
		if (StringUtils.isBlank(userId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户编码不能为空");
		}
		if (StringUtils.isBlank(mobile)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"手机号不能为空");
		}
		if (StringUtils.isBlank(validateCode)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"验证码不能为空");
		}
		// 短信验证码验证（查找最新的短信信息验证码）
		String tempCode = null;// 手机验证码
		Map tempSmsMap = new HashMap();
		tempSmsMap.put(RsSms.COL_MOBILE, mobile);
		tempSmsMap.put(RsSms.COL_SMS_TYPE_ID, Constants.RS_SMS_TYPE.UPDATE_MOBILE_CODE);
		SqlUtis.prepareSql(tempSmsMap, "", 
				SqlUtis.getSQL(tempSmsMap, "a."+ RsSms.COL_MOBILE, Types.VARCHAR, SqlUtis.EQ),
				SqlUtis.getSQL(tempSmsMap, "a."+ RsSms.COL_SMS_TYPE_ID, Types.VARCHAR, SqlUtis.EQ), SqlUtis
				.orderBy(" a.create_time desc nulls last"));
		Page smsPage = new Page();
		smsPage.setPageSize(1);
		List<RsSms> smsList = this.rsSmsService.list(tempSmsMap, smsPage);
		if (smsList != null && smsList.size() == 1) {
			RsSms rsSms = smsList.get(0);
			tempCode = rsSms.getMemo();
		}
		if (!validateCode.equals(tempCode)) {
			throw new BusinessException("-3210",
					"验证码不对！");
		}
		
		tempMap.put(RsUser.COL_MOBILE, mobile);
		Map formMap = new HashMap();
		formMap.put(RsUser.COL_USER_ID, userId);
		SqlUtis.prepareSql(formMap, "", SqlUtis.getSQL(formMap, "a."
				+ RsUser.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ)
				);
		RsUser user = this.one(formMap);
		if(user == null){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户不存在");
		}
		if(!user.getMobile().equals(mobile)){
			SqlUtis.prepareSql(tempMap, "", SqlUtis.getSQL(tempMap, "a."
					+ RsUser.COL_MOBILE, Types.VARCHAR,SqlUtis.EQ)
					);
			if(this.exists(tempMap)){
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
						"手机号已存在");
			}
		}
		rsUser.setMobile(mobile);
		formMap.put("rsUser", rsUser);
		int totals = this.update(formMap);
		if(totals != 1){
			return executeRerutnFail(jsonObject);
		}
		return executeRerutn(jsonObject);
	}
	
}
